package ai.zixing.mashibing.basic_class.class10;

/**
 * 图的转化工具类
 */
public class GraphGenerator {

    // matrix 所有的边
    // N*3 的矩阵
    // [weight, from节点上面的值，to节点上面的值]
    public static Graph createGraph(Integer[][] matrix) {
        Graph graph = new Graph();
        for (int i = 0; i < matrix.length; i++) {
            Integer weight = matrix[i][0];
            Integer from = matrix[i][1];
            Integer to = matrix[i][2];
            // 创建起点
            if (!graph.nodes.containsKey(from)) {
                graph.nodes.put(from, new Node(from));
            }
            // 创建终点
            if (!graph.nodes.containsKey(to)) {
                graph.nodes.put(to, new Node(to));
            }
            Node fromNode = graph.nodes.get(from);
            Node toNode = graph.nodes.get(to);
            // 创建边
            Edge newEdge = new Edge(weight, fromNode, toNode);
            // 终点是起点的邻居点
            fromNode.nexts.add(toNode);
            // 起点出度++
            fromNode.out++;
            // 终点入度++
            toNode.in++;
            // 创建的边是 fromNode 的一条边
            fromNode.edges.add(newEdge);
            // 也是图的边
            graph.edges.add(newEdge);
        }
        return graph;
    }
}
